package com.hspedu.com.jdbc.datasource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author DL5O
 * @version 1.0
 * 演示c3p0的使用
 */
public class C3P0_ {

    @Test
    //方式1：相关参数，在程序中指定user，url，password等
    public void testC3P0_01() throws IOException, PropertyVetoException, SQLException {
        //1.创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //2.通过配置文件mysql.properties 获取相关的连接信息
        //在static代码块中去初始化
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\jdbc.properties"));
        //读取相关的属性值
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");

        //给数据源 comboPooledDataSource 设置相关的信息
        //注意：连接管理是由comboPooledDataSource 来管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);

        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);//会存放10个已经连好的连接
        //最大连接数
        comboPooledDataSource.setMaxPoolSize(50);

        //测试连接池的效率，测试mysql 5000次操作
        long start = System.currentTimeMillis();

        for (int i = 0; i < 500000; i++) {
            Connection connection = comboPooledDataSource.getConnection();//这个方法就是从DataSource接口实现的
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("C3P0 5000次连接MySql 耗时=" + (end - start));//2931
    }

    //第二种方式 使用配置文件模板来完成
    //1.将C3P0 提供的 c3p0-config.xml 拷贝到src目录下
    //2.该文件指定了连接数据库和连接池的相关参数
    public void testC3P0_02() throws SQLException {
        //1.写入 数据源名称
        ComboPooledDataSource ywl_edu = new ComboPooledDataSource("ywl_edu");

        //测试5000次
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            Connection connection = ywl_edu.getConnection();
            connection.close();
        }
        System.out.println("连接OK~");
        long end = System.currentTimeMillis();
        System.out.println("C3P0第二种方式 耗时:" + (end - start));//589
    }
}
